import pygame.font
from pygame.sprite import Group

from ship import Ship


class ScoreBoard:
    """得分统计"""

    def __init__(self, settings, screen, stats):
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.settings = settings
        self.stats = stats

        # 显示得分字体设置
        self.text_color = (30, 30, 30)
        self.font = pygame.font.SysFont('fangsong', 25)
        # 初始得分图像
        self.pre_score()
        # 最高得分记录
        self.pre_high_score()
        # 游戏等级
        self.pre_level()
        # 显示飞船剩余量，绘制飞船图像
        self.pre_ships()

    def pre_ships(self):
        """剩余飞船量"""
        # 创建飞船编组
        self.ships = Group()
        for ship_number in range(self.stats.ship_left):
            ship = Ship(self.settings, self.screen)
            ship.rect.x = 10 + ship_number * ship.rect.width
            ship.rect.y = 10
            self.ships.add(ship)

    def pre_score(self):
        """得分板设置"""
        # 将第二个实参指定为负数，round() 将圆整到最近的10、100、1000等整数倍。
        rounded_score = int(round(self.stats.score, -1))
        score_str = "{:,}".format(rounded_score)
        self.score_image = self.font.render("SCORE:" + score_str, True, self.text_color, self.settings.bg_color)
        # 屏幕右上角显示
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.score_rect.top = 20

    def pre_level(self):
        """游戏等级显示"""
        self.level_image = self.font.render("LEVEL:" + str(self.stats.level), True, self.text_color,
                                            self.settings.bg_color)
        # 得分统计下面显示游戏等级
        self.level_rect = self.level_image.get_rect()
        self.level_rect.right = self.score_rect.right
        self.level_rect.top = self.score_rect.bottom + 10

    def pre_high_score(self):
        """最高得分记录"""
        rounded_score = int(round(self.stats.high_score, -1))
        score_str = "{:,}".format(rounded_score)
        self.high_score_image = self.font.render("HIGHEST SCORE:" + score_str, True, self.text_color,
                                                 self.settings.bg_color)
        # 屏幕顶部居中显示
        self.high_score_rect = self.high_score_image.get_rect()
        self.high_score_rect.top = self.screen_rect.top
        self.high_score_rect.centerx = self.screen_rect.centerx

    def show_score(self):
        """显示当前得分,最高分,游戏等级"""
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)
        self.screen.blit(self.level_image, self.level_rect)
        # 绘制剩余飞船数
        self.ships.draw(self.screen)
